/*
 * @Author: Mr.Cong Wei
 * @Date: 2022-03-29 11:58:46
 * @LastEditTime: 2022-10-08 13:09:18
 */
import { RouteRecordRaw, createRouter, createWebHistory } from 'vue-router'
import { storeToRefs } from 'pinia'
import useKeepAliveHook from '../store/keepAlive'

const modules = import.meta.globEager('./modules/**/*.ts')

const menuModules: RouteRecordRaw[] = []

Object.keys(modules).forEach(key => {
  const mod = modules[key].default || {}
  const modList = Array.isArray(mod) ? [...mod] : [mod]
  menuModules.push(...modList)
})

const router = createRouter({
  history: createWebHistory(),
  routes: menuModules
})

// 路由白名单
const whiteList = ['/login', '/auth']
router.beforeEach(async (to, from, next) => {
  const keepAliveStore = useKeepAliveHook()
  const { pageArray } = storeToRefs(keepAliveStore)
  const { setPageArray, setKeepAliveExclude, setActivePage, removeKeepAliveExcludeByName } = keepAliveStore

  if (whiteList.includes(to.path)) {
    return next()
  }
  const token = localStorage.getItem('token')
  if (!token) {
    return next('/login')
  } else {
    if (to.matched.length === 0) {
      //如果未匹配到路由
      from.name ? next({ name: from.name }) : next('/') //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
    } else {
      if (to.query?.clearSelfRoute === 'true') {
        const componentsName = await getComponentsName(from)
        const deleteIndex = pageArray.value.findIndex(_x => _x.origin_path === from.matched[1]?.path)
        // 删除tab对应标签页
        setPageArray(deleteIndex)
        // 删除keepAlive缓存的组件
        setKeepAliveExclude(componentsName)

        to.fullPath = to.fullPath.replace('clearSelfRoute=true', '')
        ;(to as any).href = (to as any).href.replace('clearSelfRoute=true', '')
        delete to.query?.clearSelfRoute
      }
      //  首次进入编辑会会缓存携带id的路由信息。后续再次点击编辑，返回列表，从tab切换编辑页面数据还是首次路由信息
      const findPage = pageArray.value.find(_x => _x.origin_path === to.matched[1]?.path)
      if (findPage) {
        findPage.url = to.fullPath
      } else {
        const componentsName = await getComponentsName(to)

        pageArray.value.push({
          name: to.name,
          url: to.fullPath,
          origin_path: to.matched[1]?.path,
          components_name: componentsName
        })
        removeKeepAliveExcludeByName(componentsName)
      }

      setActivePage(pageArray.value.length - 1)
      next() //如果匹配到正确跳转
    }
  }
})

const getComponentsName = async route => {
  if (route.matched[1]?.components.default instanceof Function) {
    const components = await route.matched[1]?.components.default()
    return components?.default?.name
  } else {
    return route.matched[1]?.components?.default?.name
  }
}
export default router
